<script setup lang="ts">
  import { addPatientApi, patientInfoApi, updatePatientApi } from '@/api/patient'
  import { ref } from 'vue'
  // 1. 表单数据
  const formData = ref({
    name: '',
    idCard: '',
    gender: 1,
    defaultFlag: 0,
  })
  const form = ref<UniHelper.UniFormsInstance>()
  const onSwichChange = (event: UniHelper.SwitchOnChangeEvent) => {
    // console.log(event)
    formData.value.defaultFlag = event.detail.value ? 1 : 0
  }
  const formRules: UniHelper.UniFormsRules = {
    name: {
      rules: [
        { required: true, errorMessage: '请输入患者姓名' },
        { pattern: /^[\u4e00-\u9fa5·]{2,7}$/, errorMessage: '请输入正确的姓名' },
      ],
    },
    idCard: {
      rules: [
        { required: true, errorMessage: '请输入患者身份证号' },
        {
          pattern:
            /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/,
          errorMessage: '请输入正确的身份证号',
        },
      ],
    },
    // 身份证第 17 位表示性别，奇数表示男性 1，偶数表示女性 0。
    gender: {
      rules: [
        { required: true, errorMessage: '请选择性别' },
        {
          // 自定义校验规则
          validateFunction: (rule, value, data, callback) => {
            // 判断身份证第 17 位(索引为16)是否与选择的性别一致
            if (Number(formData.value.idCard.charAt(16)) % 2 !== value) {
              // callback 处理提示错误信息
              callback('选择的性别与身份号中性别不一致')
            }
            // 验证通过返回 true
            return true
          },
        },
      ],
    },
  }
  const onSubmit = async () => {
    try {
      await form.value?.validate?.()
      if (pageParams.id) {
        await updatePatientApi({
          ...formData.value,
          id: pageParams.id,
        })
        uni.showToast({
          title: '编辑成功',
          icon: 'none',
        })
      } else {
        await addPatientApi(formData.value)
        uni.showToast({
          title: '添加成功',
          icon: 'none',
        })
      }

      uni.navigateBack()
    } catch (error) {
      console.log(error)
    }
  }
  const pageParams = defineProps<{ id: string }>()
  const getDetail = async () => {
    const res = await patientInfoApi(pageParams.id)
    formData.value = {
      name: res.name,
      idCard: res.idCard,
      gender: res.gender || 0,
      defaultFlag: res.defaultFlag,
    }
    // console.log(res)
  }
  if (pageParams.id) {
    uni.setNavigationBarTitle({ title: '编辑患者信息' })
    getDetail()
  }
</script>

<template>
  <scroll-view>
    <view class="archive-page">
      <uni-forms border label-width="220rpx" ref="form" :model="formData" :rules="formRules">
        <uni-forms-item label="患者姓名" name="name">
          <uni-easyinput
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :styles="{ color: '#121826' }"
            :input-border="false"
            :clearable="false"
            placeholder="请填写真实姓名"
            v-model="formData.name"
          />
        </uni-forms-item>
        <uni-forms-item label="患者身份证号" name="idCard">
          <uni-easyinput
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :styles="{ color: '#121826'}"
            :input-border="false"
            :clearable="false"
            placeholder="请填写身份证号"
            v-model="formData.idCard"
          />
        </uni-forms-item>
        <uni-forms-item label="患者性别" name="gender">
          <uni-data-checkbox
            selectedColor="#16C2A3"
            :localdata="[
              { text: '男', value: 1 },
              { text: '女', value: 0 },
            ]"
            v-model="formData.gender"
          />
        </uni-forms-item>
        <uni-forms-item label="默认就诊人" name="name">
          <view class="uni-switch">
            <switch checked color="#20c6b2" style="transform: scale(0.7)" @change="onSwichChange" />
          </view>
        </uni-forms-item>
        <button class="uni-button" @click="onSubmit()">保存</button>
      </uni-forms>
    </view>
    <!-- {{ formData }} -->
  </scroll-view>
</template>

<style lang="scss">
  @import './index.scss';
</style>
